#!/usr/bin/env bash
export LC_ALL="en_US.UTF-8"
artifact="%artifact"
job_name="%job_name"
run_dir="%run_dir"

run_dir=`cd "$run_dir"; pwd`

start_time=`date +%%Y%%m%%d-%%H%%M%%S`

pid=`echo $$`

package_dir="$run_dir/package"
log_dir="$run_dir/log"
pid_file="$run_dir/${job_name}.pid"

if [[ ! -d $run_dir/stdout ]]; then 
   mkdir $run_dir/stdout
fi

output_file="$run_dir/stdout/${job_name}_${start_time}.out"

jar_dirs="%jar_dirs"
params="%params"

java="/opt/soft/jdk/bin/java"
if ! [ -e $java ]; then
  java="/usr/bin/java"
fi

class_path="$run_dir/:$jar_dirs"

if [ -f $pid_file ]; then
  if kill -0 `cat $pid_file` > /dev/null 2>&1; then
    echo -e "\033[33mThe $job_name is running, skipped.\033[0m"
    exit 0
  else
    rm -f "$pid_file" || exit 1
  fi
fi

options=""
if [ -d "$package_dir/lib/native" ]; then
  JAVA_PLATFORM=""
  if [ -z $JAVA_PLATFORM ]; then
    JAVA_PLATFORM=`CLASSPATH=${class_path} ${java} org.apache.hadoop.util.PlatformName | sed -e "s/ /_/g"`
  fi

  JAVA_LIBRARY_PATH="$JAVA_LIBRARY_PATH:$package_dir/lib/native/:$package_dir/lib/native/${JAVA_PLATFORM}"

  export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$JAVA_LIBRARY_PATH"
  options="$OPTS -Djava.library.path=$JAVA_LIBRARY_PATH"
fi

%service_env
if [ -f ./pre.sh ]; then
  source ./pre.sh $job_name $run_dir
fi
exec ${java} -cp $class_path $options $params $@ 1>$output_file 2>&1
